<?php

/**
 * This class extends the metadata management for MEF giving a richer metadata
 * sintax which consists in <code>@export-metadata Annotation:Param1:Param2</code>
 *
 * @author JeyDotC
 */
class MetadataCollection {

    private $metadata = array();

    /**
     * Creates a MetadataCollection instance.
     * @param array $metadata The metadata for a class.
     */
    function __construct(array $metadata = array()) {
        $this->metadata = $metadata;
    }

    /**
     * Checks if the class has an annotation regardless the params.
     * 
     * @param string $annotation
     * @return boolean true if the class is annotated with the given annotation.
     */
    public function has($annotation) {
        return $this->annotationExists($this->metadata, $annotation);
    }

    /**
     * Determines if the given member of the class has the given annotation.
     * 
     * @param string $member The class member to find the annotation.
     * @param string $annotation The annotation to be looked for.
     * @return boolean true if the class's member is annotated with the given annotation. 
     */
    public function hasByMember($member, $annotation) {
        $result = false;
        if(array_key_exists($member, $this->metadata)){
            $result = $this->annotationExists($this->metadata[$member], $annotation);
        }
        
        return $result;
    }

    /**
     * Finds the class's annotation with it's params.
     * 
     * @param string $annotation The annotation to be looked for.
     * @return string The annotation with it's params.
     */
    public function find($annotation) {
        return $this->findAnnotation($this->metadata, $annotation);
    }

    /**
     * Finds the annotation for the given member of the class.
     * 
     * @param string $member The class member to find the annotation.
     * @param string $annotation The annotation to be looked for.
     * @return string The annotation with it's params.
     */
    public function findByMember($member, $annotation) {
        $result = "";
        if(array_key_exists($member, $this->metadata)){
            $result = $this->findAnnotation($this->metadata[$member], $annotation);
        }
        
        return $result;
    }

    private function annotationExists(array $annotationList, $annotation) {
        $result = false;

        foreach ($annotationList as $meta) {
            if (strpos((string) $meta, (string) $annotation) === 0) {
                $result = true;
                break;
            }
        }

        return $result;
    }

    private function findAnnotation(array $annotationList, $annotation) {
        $result = "";

        foreach ($annotationList as $meta) {
            if (strpos((string) $meta, (string) $annotation) === 0) {
                $result = $meta;
                break;
            }
        }

        return $result;
    }

}

?>
